﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using MapControl.Misc.DAL;
using MapControl.Misc.GPSPoint;
using MITI;

namespace MapControl.Misc
{
    public static class GeneralClass
    {
        public static int FULL_DATA_LEN = 39;
        public static int DATA_LEN = 36;
        public static int NAME_LEN = 4;
        public static int LAT_LEN = 8;
        public static int LON_LEN = 9;
        public static int ALT_LEN = 4;
        public static int SPEED_LEN = 3;
        public static int ANGLE_LEN = 3;

        public static ComPort objPort; //Cổng COM
        public static DataTable dbTestGPS; //Datatable lưu danh sách các tọa độ gps
        public static BaseGPSPoint currGPSData; //Tọa độ GPS mới nhất
        public static Airport objCurrAirport; //Sân bay đang chọn
        public static bool IsViewAirport = false; //Cho biết hiện/ẩn sân bay
        public static string dbFileName = "gpsdata.sdf"; //Tên file CSDL đang kết nối

        /// <summary>
        /// Kết nối CSDL theo CSDL hiện tại
        /// Kiểm tra CSDL ngày hôm nay đã tạo chưa
        /// Nếu chưa thì backup CSDL hiện tại như là ngày hôm qua
        /// Còn CSDL ngày hôm nay chính là file gpsdata.sdf
        /// </summary>
        public static string ConnectDatabase()
        {
            try
            {
                //==========================================================
                //Kiểm tra file db có tồn tại không
                string dbName = "gpsdata.sdf";
                if (!File.Exists(dbName))
                    return string.Format("File {0} không tồn tại", dbName);
                //Kết nối đến CSDL mặc định
                GeneralClass.dbFileName = dbName;
                BaseDBCe.g_ConnectStr = string.Format("DataSource={0}; Password=''", GeneralClass.dbFileName); // Properties.Resources.ConnectString;

                //==========================================================
                //Kiểm tra dữ liệu đã backup chưa. Nếu chưa thì backup
                DateTime dt = DateTime.Now.Date.AddDays(-1);
                string dbFileName = string.Format("gpsdata_{0}-{1}-{2}.sdf", dt.Day, dt.Month, dt.Year);
                string filepath = "BackupData\\" + dbFileName;
                if (!File.Exists(filepath))
                {
                    File.Copy(dbName, filepath);
                    GPSDataRepository.DeleteAll();
                }
                //BaseDBCe.Upgrade();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "";

        }

        ///// <summary>
        ///// Lưu vào CSDL
        ///// </summary>
        //public static void SaveIntoDataBase(BaseGPSPoint gps)
        //{
        //    //Lưu vào CSDL
        //    string sql = string.Format("insert into gpsdata(localtime, name, lat, lon, alt, speed, angle) values ('{0}','{1}',{2},{3},{4},{5},{6})", gps.LocalTime, gps.Name, gps.LatGPS, gps.LonGPS, gps.Alt, gps.Speed, gps.Angle);
        //    BaseDBCe.ExecSql_NoneQuery(sql);
        //}

        //public static void LoadDataBase()
        //{
        //    string sql = "select * from gpsdata";
        //    dbTestGPS = BaseDBCe.ExecSql_DataSet(sql).Tables[0];
        //}

        //public static void DeleteAllData()
        //{
        //    string sql = "delete from gpsdata";
        //    BaseDBCe.ExecSql_NoneQuery(sql);

        //}

        //public static void GetPlane()
        //{
        //    string sql = "delete from gpsdata";
        //    BaseDBCe.ExecSql_NoneQuery(sql);

        //}

        //public static GPSPoint GetGPSData(AxMapXLib.AxMap map, DataRow row)
        //{
        //    DateTime localTime = DateTime.Parse(row["localtime"].ToString());
        //    string name = row["name"].ToString();
        //    double lon = double.Parse(row["lon"].ToString());
        //    double lat = double.Parse(row["lat"].ToString());
        //    double alt = double.Parse(row["alt"].ToString());
        //    double speed = double.Parse(row["speed"].ToString());
        //    double angle = double.Parse(row["angle"].ToString());
        //    GPSPoint obj = new GPSPoint(map, name, localTime, lon, lat, alt, speed, angle);

        //    return obj;
        //}

        //public static string ConvertDecimalToDMSCoordinate(double coord)
        //{
        //    int sec = (int)Math.Round(coord * 3600);
        //    int deg = sec / 3600;
        //    sec = Math.Abs(sec % 3600);
        //    int min = sec / 60;
        //    sec %= 60;
        //    string value = string.Format("{0}°{1}'{2}\"", deg, min, sec);
        //    return value;
        //}

        //public static double ConvertDMSToDecimalCoordinate(double degrees, double minutes, double seconds)
        //{
        //    //Decimal degrees = 
        //    //   whole number of degrees, 
        //    //   plus minutes divided by 60, 
        //    //   plus seconds divided by 3600

        //    return degrees + (minutes / 60) + (seconds / 3600);
        //}

        /// <summary>
        /// http://en.wikipedia.org/wiki/Geographic_coordinate_conversion
        /// Input a double latitude or longitude in the decimal format
        /// e.g. 87.728056
        /// </summary>
        /// <param name="coord"></param>
        /// <returns></returns>
        public static string DecimalToDMS(double coord)
        {
            string output, degrees, minutes, seconds;

            // gets the modulus the coordinate divided by one (MOD1).
            // in other words gets all the numbers after the decimal point.
            // e.g. mod = 87.728056 % 1 == 0.728056
            //
            // next get the integer part of the coord. On other words the whole number part.
            // e.g. intPart = 87

            double mod = coord % 1;
            int intPart = (int)coord;

            //set degrees to the value of intPart
            //e.g. degrees = "87"

            degrees = intPart.ToString();

            // next times the MOD1 of degrees by 60 so we can find the integer part for minutes.
            // get the MOD1 of the new coord to find the numbers after the decimal point.
            // e.g. coord = 0.728056 * 60 == 43.68336
            //      mod = 43.68336 % 1 == 0.68336
            //
            // next get the value of the integer part of the coord.
            // e.g. intPart = 43

            coord = mod * 60;
            mod = coord % 1;
            intPart = (int)coord;

            // set minutes to the value of intPart.
            // e.g. minutes = "43"
            minutes = intPart.ToString();

            //do the same again for minutes
            //e.g. coord = 0.68336 * 60 == 41.0016
            //e.g. intPart = 41
            coord = mod * 60;
            intPart = (int)coord;

            // set seconds to the value of intPart.
            // e.g. seconds = "41"
            seconds = intPart.ToString();

            // I used this format for android but you can change it 
            // to return in whatever format you like
            // e.g. output = "87/1,43/1,41/1"
            //output = degrees + "/1," + minutes + "/1," + seconds + "/1";

            //Standard output of D°M′S″
            output = degrees + "°" + minutes + "'" + seconds + "\"";

            return output;
        }

        /*
         * Conversion DMS to decimal 
         *
         * Input: latitude or longitude in the DMS format ( example: N 43° 36' 15.894")
         * Return: latitude or longitude in decimal format   
         * hemisphereOUmeridien => {W,E,S,N}
         *
         */
        public static double DMSToDecimal(string hemisphereOUmeridien, double degres, double minutes, double secondes)
        {
            double LatOrLon = 0;
            double signe = 1.0;

            if ((hemisphereOUmeridien.Equals("W")) || (hemisphereOUmeridien.Equals("S"))) { signe = -1.0; }
            LatOrLon = signe * (Math.Floor(degres) + Math.Floor(minutes) / 60.0 + secondes / 3600.0);

            return (LatOrLon);
        }

        /*
         * Conversion N10.39168, E107.13765 to decimal 
         *
         * Input: latitude or longitude in the DMS format ( example: N 43° 36' 15.894")
         * Return: latitude or longitude in decimal format   
         * hemisphereOUmeridien => {W,E,S,N}
         *
         */
        public static double StringCoordToDecimalCoord(string value)
        {
            double LatOrLon = 0;
            double signe = 1.0;
            //Lat
            string hemisphereOUmeridien = value.Substring(0,1); //{W,E,S,N}
            if ((hemisphereOUmeridien.Equals("W")) || (hemisphereOUmeridien.Equals("S"))) { signe = -1.0; }
            LatOrLon = signe * double.Parse(value.Substring(1, value.Length-1));

            return (LatOrLon);
        }
    }
}
